"use client"
import { searchQuestionVOByPage } from "@/api/question"
import { ProTable } from "@ant-design/pro-components"
import React, { useRef, useState } from "react"
import TagList from "../tag-list"
import Link from "next/link"
import type { ActionType, ProColumns } from "@ant-design/pro-components"

// 外层页面是服务端渲染，如果已经在服务端取得了数据，可以直接展示，而不用等到客户端渲染时再发起请求
// 将服务端渲染获取得的数据，传递到里层的组件中，作为组件的初始状态

interface Props {
  //  默认值（用于展示服务端渲染的数据）
  defaultQuestionList?: QuestionVO[]
  defaultTotal?: number
  // 搜索条件
  defaultSearchParams?: QuestionQueryRequest
}

/**
 * 题目列表组件
 */
const QuestionTable: React.FC<Props> = (props) => {
  const { defaultQuestionList, defaultTotal, defaultSearchParams = {} } = props
  const actionRef = useRef<ActionType>()
  // 题目列表
  const [questionList, setQuestionList] = useState<QuestionVO[]>(defaultQuestionList || [])
  // 题目总数
  const [total, setTotal] = useState<number>(defaultTotal || 0)
  // 是否是首次加载
  const [init, setInit] = useState<boolean>(true)

  /**
   * 表格列配置
   */
  const columns: ProColumns<QuestionVO>[] = [
    {
      title: "标题",
      dataIndex: "title",
      valueType: "text",
      hideInSearch: true,
      render: (_, record) => {
        return <Link href={`/question/${record.id}`}>{record.title}</Link>
      }
    },
    {
      title: "搜索",
      dataIndex: "searchText",
      valueType: "text",
      hideInTable: true
    },
    {
      title: "标签",
      dataIndex: "tags",
      valueType: "select",
      fieldProps: {
        mode: "tags"
      },
      render: (_, record) => {
        return <TagList tags={record.tagList} />
      }
    }
  ]

  return (
    <div className="question-table">
      <ProTable<QuestionVO>
        actionRef={actionRef}
        size="large"
        search={{
          labelWidth: "auto"
        }}
        form={{
          initialValues: defaultSearchParams
        }}
        pagination={{
          pageSize: 12,
          total: total,
          showSizeChanger: false,
          showTotal: (total) => `总共 ${total} 条`
        }}
        dataSource={questionList}
        request={async (params, sort, filter) => {
          // 首次请求
          if (init) {
            setInit(false)
            // 如果已有外层传来的默认数据，无需再次查询
            if (defaultQuestionList && defaultTotal) {
              return {
                success: true,
                data: defaultQuestionList,
                total: defaultTotal
              }
            }
          }

          const sortField = Object.keys(sort)?.[0] || "createTime"
          const sortOrder = sort?.[sortField] || "descend"

          const { data, code } = await searchQuestionVOByPage({
            ...params,
            sortField,
            sortOrder,
            ...filter
          })

          const newData = data?.records || []
          const newTotal = data?.total || 0
          // 使用 dataSource 和 pagination 的 total 使该组件成为受控组件
          setQuestionList(newData)
          setTotal(newTotal)

          return {
            success: code === 0,
            data: newData,
            total: newTotal
          }
        }}
        columns={columns}
      />
    </div>
  )
}

export default QuestionTable
